
package com.funo.government.info.view;

import java.util.ArrayList;

import android.app.ProgressDialog;
import android.content.Context;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.FragmentStatePagerAdapter;
import android.support.v4.view.ViewPager;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TabHost;
import android.widget.TabWidget;
import android.widget.TextView;
import android.widget.Toast;

import com.funo.government.info.MainApplication;
import com.funo.government.info.R;
import com.funo.government.info.bean.NavItem;
import com.funo.government.info.constant.Constant;
import com.funo.government.info.utils.BusinessException;
import com.funo.government.info.utils.BusinessResolver.BusinessCallback;
import com.funo.government.info.utils.GovernmentResolver;
import com.funo.government.info.utils.NetUtils;
import com.funo.government.info.utils.PreferenceUtils;
import com.funo.government.info.utils.RequestTask;
import com.funo.government.info.utils.Utils;

public class MainActivity extends FragmentActivity {

    private TabHost mTabHost;

    private ViewPager mViewPager;

    private TabsAdapter mTabsAdapter;

    private RequestTask mGetNavTask;

    private ProgressDialog progressDialog;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        MainApplication ma = (MainApplication) getApplicationContext();
        ma.addActivity(this);
        if (!NetUtils.isConnected(this)) {
            Toast.makeText(this, R.string.not_network, Toast.LENGTH_LONG).show();
            return;
        }

        mTabHost = (TabHost) findViewById(android.R.id.tabhost);

        mTabHost.setup();

        mViewPager = (ViewPager) findViewById(R.id.pager);

        mViewPager.setOffscreenPageLimit(4);

        mTabsAdapter = new TabsAdapter(this, mTabHost, mViewPager);
        progressDialog = new ProgressDialog(this, ProgressDialog.STYLE_SPINNER);
        progressDialog.setMessage(getString(R.string.drop_down_list_footer_loading_text));
        String areaId = PreferenceUtils.getLocalAreaId(this);
        loadNav(areaId);
        // ArrayList<NavItem> navs = new ArrayList<NavItem>();
        // NavItem n1 = new NavItem("首页", "1", "http://www.qq.com/mobile/");
        // NavItem n2 = new NavItem("新闻", "2",
        // "http://www.qq.com/mobile/news.htm?ent");
        // NavItem n3 = new NavItem("通告", "3",
        // "http://www.qq.com/mobile/appandroid.htm");
        // navs.add(n1);
        // navs.add(n2);
        // navs.add(n3);
        // buildTab(navs);
        Utils.ProcessPullService(this);

    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.main, menu);
        return true;
    }

    @Override
    public boolean onMenuItemSelected(int featureId, MenuItem item) {
        switch (item.getItemId()) {
            case R.id.action_exit:
                finish();
                break;
        }
        return super.onMenuItemSelected(featureId, item);
    }

    public void loadNav(String areaId) {

        progressDialog.show();
        mGetNavTask = GovernmentResolver.navList(areaId,
                new BusinessCallback<ArrayList<NavItem>>() {

                    @Override
                    public void onSuccess(ArrayList<NavItem> t) {
                        progressDialog.dismiss();
                        buildTab(t);
                    }

                    @Override
                    public void onError(BusinessException e) {
                        progressDialog.dismiss();
                        Toast.makeText(MainActivity.this, R.string.cannot_connect_server,
                                Toast.LENGTH_SHORT).show();
                        e.printStackTrace();
                    }
                });
    }

    public void buildTab(ArrayList<NavItem> navs) {
        mTabsAdapter.clearTabs();
        Bundle bundle = new Bundle();
        View view;
        TextView tvTitle;
        ImageView ivIcon;

        for (NavItem item : navs) {
            view = getLayoutInflater().inflate(R.layout.tabhost_item, null);
            tvTitle = (TextView) view.findViewById(R.id.tvTitle);
            ivIcon = (ImageView) view.findViewById(R.id.ivIcon);
            tvTitle.setText(item.chnlname);
            Integer resId = Constant.NAV_ICON_MAP.get(item.chnlId);
            if (resId != null) {
                ivIcon.setImageResource(resId);
            } else {
                ivIcon.setImageResource(R.drawable.tab_home);
            }
            bundle = new Bundle();
            bundle.putString("link", item.linkUrl);
            mTabsAdapter.addTab(mTabHost.newTabSpec(item.chnlname).setIndicator(view),
                    WebFragment.class, bundle);
        }
        view = getLayoutInflater().inflate(R.layout.tabhost_item, null);
        tvTitle = (TextView) view.findViewById(R.id.tvTitle);
        ivIcon = (ImageView) view.findViewById(R.id.ivIcon);
        tvTitle.setText(R.string.more);
        ivIcon.setImageResource(R.drawable.tab_more);
        mTabsAdapter.addTab(mTabHost.newTabSpec(getString(R.string.more)).setIndicator(view),
                MoreFragment.class, bundle);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (mGetNavTask != null) {
            mGetNavTask.cancel(true);
            mGetNavTask = null;
        }
    }

    public class TabsAdapter extends FragmentStatePagerAdapter implements
            TabHost.OnTabChangeListener, ViewPager.OnPageChangeListener {
        private final Context mContext;

        private final TabHost mTabHost;

        private final ViewPager mViewPager;

        private int selectTabPosition;

        private final ArrayList<TabInfo> mTabs = new ArrayList<TabInfo>();

        final class TabInfo {
            private final String tag;

            private final Class<?> clss;

            private final Bundle args;

            TabInfo(String _tag, Class<?> _class, Bundle _args) {
                tag = _tag;
                clss = _class;
                args = _args;
            }
        }

        class DummyTabFactory implements TabHost.TabContentFactory {
            private final Context mContext;

            public DummyTabFactory(Context context) {
                mContext = context;
            }

            @Override
            public View createTabContent(String tag) {
                View v = new View(mContext);
                v.setMinimumWidth(0);
                v.setMinimumHeight(0);
                return v;
            }
        }

        public TabsAdapter(FragmentActivity activity, TabHost tabHost, ViewPager pager) {
            super(activity.getSupportFragmentManager());
            mContext = activity;
            mTabHost = tabHost;
            mViewPager = pager;
            mTabHost.setOnTabChangedListener(this);

            mViewPager.setAdapter(this);
            mViewPager.setOnPageChangeListener(this);
        }

        public void addTab(TabHost.TabSpec tabSpec, Class<?> clss, Bundle args) {
            tabSpec.setContent(new DummyTabFactory(mContext));
            String tag = tabSpec.getTag();

            TabInfo info = new TabInfo(tag, clss, args);
            mTabs.add(info);

            notifyDataSetChanged();
            mTabHost.addTab(tabSpec);
            int length = mTabHost.getTabWidget().getChildCount();
            for (int i = 0; i < length; i++) {
                final int index = i;
                mTabHost.getTabWidget().getChildAt(i).setOnClickListener(new OnClickListener() {

                    @Override
                    public void onClick(View v) {
                        if (selectTabPosition == index) {
                            Fragment fragment = (Fragment) mTabsAdapter.instantiateItem(mViewPager,
                                    index);
                            if (fragment instanceof WebFragment) {
                                ((WebFragment) fragment).reload();
                            }
                        }
                        mTabHost.setCurrentTab(index);
                        selectTabPosition = index;
                    }
                });

            }

        }

        public void clearTabs() {
            mTabs.clear();
            mTabHost.clearAllTabs();
            notifyDataSetChanged();

        }

        @Override
        public int getCount() {
            return mTabs.size();
        }

        @Override
        public Fragment getItem(int position) {
            TabInfo info = mTabs.get(position);
            return Fragment.instantiate(mContext, info.clss.getName(), info.args);
        }

        public int getItemPosition(Object object) {
            return POSITION_NONE;
        }

        @Override
        public void onTabChanged(String tabId) {

            int position = mTabHost.getCurrentTab();
            mViewPager.setCurrentItem(position);
            selectTabPosition = position;
            TextView tvTitle;
            for (int i = 0; i < mTabHost.getTabWidget().getChildCount(); i++) {
                tvTitle = (TextView) mTabHost.getTabWidget().getChildAt(i)
                        .findViewById(R.id.tvTitle);
                if (i == position) {
                    tvTitle.setTextColor(mContext.getResources()
                            .getColor(R.color.font_tab_selected));
                } else {
                    tvTitle.setTextColor(mContext.getResources().getColor(
                            R.color.font_tab_unselected));
                }

            }

        }

        @Override
        public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
        }

        @Override
        public void onPageSelected(int position) {
            // Unfortunately when TabHost changes the current tab, it kindly
            // also takes care of putting focus on it when not in touch mode.
            // The jerk.
            // This hack tries to prevent this from pulling focus out of our
            // ViewPager.
            TabWidget widget = mTabHost.getTabWidget();
            int oldFocusability = widget.getDescendantFocusability();
            widget.setDescendantFocusability(ViewGroup.FOCUS_BLOCK_DESCENDANTS);
            mTabHost.setCurrentTab(position);
            widget.setDescendantFocusability(oldFocusability);
        }

        @Override
        public void onPageScrollStateChanged(int state) {
        }
    }

}
